package abq2.jic.jic.plugin.operate.course;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.control.Control;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.Date;
import java.util.EventObject;
import java.util.List;

public class CourseConfirm extends AbstractFormPlugin {
    private Log courseConfirmLog= LogFactory.getLog("CourseConfirm");

    @Override
    public void afterCreateNewData(EventObject e) {
        Object primaryKey = this.getView().getFormShowParameter().getCustomParam("courseId");
        if (primaryKey != null) {
            this.getModel().setValue("abq2_course",primaryKey);
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("btnok");
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        Control source = (Control) evt.getSource();
        if (source.getKey().equals("btnok")){
            Object primaryKey = this.getView().getFormShowParameter().getCustomParam("courseId");
            QFilter idFilter = new QFilter("id", QCP.equals,primaryKey);


            DynamicObject[] myCourses = BusinessDataServiceHelper.load("abq2_my_course",
                    "abq2_my_course_stu," + //课程内码
                            "name," + //课程名称
                            "abq2_textfield3," + //星期
                            "abq2_textfield1," + //教室
                            "abq2_textfield," + //教师
                            "abq2_textfield4," + //年级
                            "creator," + //学生
                            "abq2_textfield2",  //课节
                    new QFilter[]{new QFilter("creator",QCP.equals, RequestContext.get().getCurrUserId())});

            DynamicObject optionCourse = BusinessDataServiceHelper.loadSingle("abq2_stu_course",
                    "id," + //内码
                            "name," +//名称
                            "abq2_combofield1," + //星期
                            "abq2_classroom," + //教室
                            "abq2_textfield1," + //教师
                            "abq2_combofield," + //年级
                            "abq2_integerfield," + //课程人数
                            "abq2_integerfield1," + //已选人数
                            "abq2_mulcombofield",  //课节
                    new QFilter[]{idFilter});
           //如果课程有误，就弹出弹窗，如果课程为空，就弹窗。
            if (optionCourse == null){
                this.getView().showTipNotification("课程信息有误，请重新选择");
                return;
            }
//将信息存入课程信息中
            int sum = optionCourse.getInt("abq2_integerfield");
            int already = optionCourse.getInt("abq2_integerfield1");
            int enableNum = sum - already; //剩余人数
            if (enableNum < 1){
                this.getView().showTipNotification("课程已满，无法选择该课程");
                return;
            }

            if (myCourses != null) {
                boolean failChooseCourse = false;
                String day = optionCourse.getString("abq2_combofield1"); //目标的课程的周几
                String classTimes = optionCourse.getString("abq2_mulcombofield"); //课节分开来
                String conflictInfo = "";
                for (DynamicObject myCours : myCourses) {
                    boolean conflict = false;
                    //如果课程的周几和目标课程的周几冲突，还要判断课节是否冲突
                    String myday = myCours.getString("abq2_textfield3");
                    if (myday.equals(day)){
                        //如果课程的课节与目标课程冲突
                        //判断课节是否冲突
                        String myClassTimes = myCours.getString("abq2_textfield2");
                        if (myClassTimes.equals(classTimes)) {
                            failChooseCourse = true; //确认是无法选课
                            conflict = true;  //确认存在冲突
                        }


                        if (conflict){
                            String courseName = myCours.getString("name");
                            String courseDay = myCours.getString("abq2_textfield3");
                            String courseTime = myCours.getString("abq2_textfield2").replaceAll(","," ");
                            if (myCours.getLong("abq2_my_course_stu.id")  == (Long)optionCourse.getPkValue()){
                                conflictInfo += "此课程你已经选择过了，不用重复选课";
                            }else {
                                String week = "";
                                if (courseDay.equals("1")){
                                    week = "一";
                                }else if (courseDay.equals("2")){
                                    week = "二";
                                } else if (courseDay.equals("3")) {
                                    week = "三";
                                } else if (courseDay.equals("4")) {
                                    week = "四";
                                } else if (courseDay.equals("5")) {
                                    week = "六";
                                } else if (courseDay.equals("7")) {
                                    week = "七";
                                }
                                conflictInfo += "你的 星期" + week + " 的第" + courseTime + "课的 " + courseName + " 这节课与要选的课程有冲突，请选择其他课程。" + '\n';
                            }
                        }
                    }
                }

                if (failChooseCourse){
                    this.getView().showTipNotification(conflictInfo);
                    return;
                }
            }


            DynamicObject myCourse = BusinessDataServiceHelper.newDynamicObject("abq2_my_course");
            StringBuilder sb1 = new StringBuilder(); //生成一个单据编号
            sb1.append("MYSTUCOURSE-");
            for (int i = 1; i <= 10; i++) {
                int ascii = 48 + (int) (Math.random() * 9);
                char c = (char) ascii;
                sb1.append(c);
            }
            myCourse.set("abq2_my_course_stu",optionCourse.getString("id"));
            myCourse.set("number",sb1);
            myCourse.set("name",optionCourse.getString("name"));
            myCourse.set("status","C");
            myCourse.set("abq2_datefield",new Date());
            myCourse.set("creator",RequestContext.get().getCurrUserId());
            myCourse.set("abq2_textfield",optionCourse.getString("abq2_textfield1"));
            myCourse.set("abq2_textfield1",optionCourse.getString("abq2_classroom"));
            myCourse.set("abq2_textfield4",optionCourse.getString("abq2_combofield"));
            myCourse.set("abq2_textfield2",optionCourse.getString("abq2_mulcombofield"));
            myCourse.set("abq2_textfield3",optionCourse.getString("abq2_combofield1"));

            OperationResult saveOperate = SaveServiceHelper.saveOperate("abq2_my_course", new DynamicObject[]{myCourse}, null);
            List<Object> successPkIds = saveOperate.getSuccessPkIds();
            optionCourse.set("abq2_integerfield1",optionCourse.getInt("abq2_integerfield1") + 1);
            SaveServiceHelper.update(optionCourse);

            System.out.println(successPkIds.get(0));
            this.getView().returnDataToParent(true);
            this.getView().close();
        }
    }
}
